<template>
  <van-nav-bar title="商品详情" left-text="返回" left-arrow @click-left="onClickLeft" />

  <van-swipe :autoplay="3000" lazy-render>
    <van-swipe-item v-for="image in productObj.imgs" :key="image">
      <img :src="image" width="100%" />
    </van-swipe-item>
  </van-swipe>

  <h1>{{ productObj.proname }}</h1>
  <div>{{ productObj.category }}</div>
  <div>{{ productObj.originprice }}</div>
  <div>{{ productObj.desc }}</div>

  <van-action-bar>
    <van-action-bar-icon icon="chat-o" text="客服" dot />
    <van-action-bar-icon
      icon="cart-o"
      text="购物车"
      :badge="countNum"
      @click="$router.push('/cart')"
    />
    <van-action-bar-icon icon="shop-o" text="店铺" badge="12" />
    <van-action-bar-button type="warning" text="加入购物车" @click="onCartAddClick" />
    <van-action-bar-button type="danger" text="立即购买" />
  </van-action-bar>
</template>
<script>
import { cartAddAPI } from "@/api/cart";
import { getProductDetailAPI } from "@/api/home";
import { cartArr, getCartList, countNum } from "@/store/cart";
import { getToken, getUid } from "@/utils/token";
import { showConfirmDialog, showSuccessToast } from "vant";

export default {
  name: "DetailView",
  setup() {
    return { countNum };
  },
  data() {
    return {
      productObj: {},
    };
  },
  methods: {
    onClickLeft() {
      this.$router.back();
    },
    async onCartAddClick() {
      //调用加购物车接口
      //
      // let token = localStorage.getItem("xxMallToken");
      let token = getToken();
      if (token) {
        //存在 说明登陆了，调用加入购物侧接口
        //
        let userid = getUid();
        let pid = this.$route.query.id;

        let res = await cartAddAPI(userid, pid, 1);
        console.log(res.data);
        showSuccessToast(res.data.message);

        getCartList();
      } else {
        // 没有的登录-弹出一个提示
        showConfirmDialog({
          title: "注意",
          message: "您没有登录，请登录",
        })
          .then(() => {
            // on confirm
            this.$router.push("/login");
          })
          .catch(() => {
            // on cancel
          });
      }
    },
  },
  mounted() {
    console.log(this.$route.query.id);
  },
  async created() {
    let pid = this.$route.query.id;
    let { data } = await getProductDetailAPI(pid);
    console.log(data);
    this.productObj = data.data;
  },
};
</script>
<style lang="css" scoped></style>
